import React, { useState, useCallback } from 'react';
import { message, Form, Input, Button } from 'antd';
import { eventTrack } from '@/utils/track';
import { getMailName, fetchMailBind } from '@/services/mail';
import { history } from 'umi'
import styles from './index.less';

// 邮件授权页  ---从外链进入 携带key值获取到邮箱名和usercode
const AuthorOutEmail = ({ form, location }) => {
    const { key = null } = location.query;
    const [userInfo, setUserInfo] = useState({});
    const [loading, setLoading] = useState(false);

    const handleMail = useCallback(async () => {
        const res = await getMailName({
            key
        });
        if (res.code === 10000 && res.data) {
            setUserInfo({ email: res.data.email, userCode: res.data.userCode });

            // 埋点 外链进来解析成功
            eventTrack({ eventName: 'mail_link_click', loginId: res.data.email });
        } else if (res.code === 20019) {
            history.push('/user/failed');
        } else {
            message.error('邮箱名称获取失败');
        }
    }, []);

    React.useEffect(() => {
        if (key) {
            handleMail();
        }
    }, []);

    // 表单提交
    const handleSubmit = e => {
        e.preventDefault();
        form.validateFields(async (err, values) => {
            if (err) {
                return;
            }
            const { email, emailPwd } = values;
            const payload = {
                userCode: userInfo.userCode,
                email,
                emailPwd
            };
            setLoading(true);

            // 添加邮箱
            const result = await fetchMailBind(payload);

            if (result && result.code === 10000) {
                message.success('授权完成');

                // 埋点
                await eventTrack({
                    eventName: 'mail_link_confirm_authorization_click',
                    eventProps: { authorization_status: 0 },
                    loginId: email
                });
                if (localStorage.getItem('user')) {
                    history.push('/personal/portal');
                } else {
                    history.push('/user/login');
                }
            } else {
                message.error(result.msg);

                // 埋点
                eventTrack({
                    eventName: 'mail_link_confirm_authorization_click',
                    eventProps: { authorization_status: 1, error_info: result.msg },
                    loginId: values.email
                });
            }
            setLoading(false);
        });
    };

    return (
        <div className={styles.main}>
            <div className={styles.h3}>申请授权在微微集团管理系统上管理企业邮箱</div>
            <Form
                onSubmit={handleSubmit}
                hideRequiredMark
                labelAlign="right"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 18 }}
            >
                <Form.Item label="邮箱账号">
                    {form.getFieldDecorator('email', { initialValue: userInfo.email })(
                        <Input disabled autoComplete="off" />
                    )}
                </Form.Item>
                <Form.Item label="邮箱密码">
                    {form.getFieldDecorator('emailPwd', {
                        rules: [{ required: true, message: '密码不能为空' }]
                    })(<Input autoComplete="new-password" placeholder="请输入邮箱密码" type="password" />)}
                </Form.Item>
                <Form.Item labelCol={{ span: 4 }} wrapperCol={{ offset: 4 }}>
                    <Button type="primary" htmlType="submit" loading={loading}>
                        确认授权
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
};

export default Form.create({ name: 'AuthorOutEmail' })(AuthorOutEmail);
